package com.ts.api.module.api.convert.receive.handler;

import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.common.context.ApiContext;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.module.api.convert.receive.context.ApiReceiveExistConvertContext;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveDecrypt;
import com.ts.api.module.api.convert.receive.entity.ApiReceivePhoneMd5DataExchange;
import com.ts.api.module.api.entity.ApiUserRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class DelegatingApiReceiveExistHandler implements ApiReceiveExistConvertHandler {

    @Autowired
    private ApiReceiveExistConvertContext apiReceiveExistConvertContext;

    @Override
    public ApiReceiveDecrypt decrypt(RequestVO requestVO) {
        try {
            String clientId = ApiContext.CLIENT_ID.get();
            return apiReceiveExistConvertContext.getReceiveExist(clientId).decrypt(requestVO);
        } catch (ApiMsgException apiMsgException) {
            throw apiMsgException;
        } catch (Exception e) {
            throw new ApiMsgException(ApiEnum.API_RECEIVE_DECRYPT_ERROR, e);
        }
    }

    @Override
    public ApiUserRequest parseDataExchange(ApiReceiveDecrypt apiReceiveDecrypt) {
        try {
            String clientId = ApiContext.CLIENT_ID.get();
            ApiUserRequest apiUserRequest = apiReceiveExistConvertContext.getReceiveExist(clientId).parseDataExchange(apiReceiveDecrypt);
            if (apiUserRequest == null) {
                throw new ApiMsgException(ApiEnum.API_RECEIVE_PARSE_DATA_EXCHANGE_NULL);
            }
            return apiUserRequest;
        } catch (ApiMsgException apiMsgException) {
            throw apiMsgException;
        } catch (Exception e) {
            throw new ApiMsgException(ApiEnum.API_RECEIVE_PARSE_DATA_EXCHANGE_ERROR, e);
        }
    }

    @Override
    public Map<String, Object> respDataExchange(ApiReceivePhoneMd5DataExchange dataExchangeMessage) {
        try {
            String clientId = ApiContext.CLIENT_ID.get();
            return apiReceiveExistConvertContext.getReceiveExist(clientId).respDataExchange(dataExchangeMessage);
        } catch (ApiMsgException apiMsgException) {
            throw apiMsgException;
        } catch (Exception e) {
            throw new ApiMsgException(ApiEnum.API_RECEIVE_RESP_DATA_EXCHANGE_ERROR, e);
        }
    }
}
